package com.atguigu.gulimall.member.service.impl;

import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.ex.PhoneExsitException;
import com.atguigu.gulimall.member.ex.UserNameExsitException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.atguigu.gulimall.member.vo.UserLoginVo;
import com.atguigu.gulimall.member.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;
import org.springframework.util.Assert;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regUser(UserRegisterVo userRegisterVo) {
        MemberEntity memberEntity = new MemberEntity();
        String userName = userRegisterVo.getUserName();
        String password = userRegisterVo.getPassword();
        String phone = userRegisterVo.getPhone();
        //校验用户名和手机号的唯一性
        checkUserNameUnique(userName);
        checkPhoneUnique(phone);

        memberEntity.setUsername(userName);
        String encodePassword = new BCryptPasswordEncoder().encode(password);
        memberEntity.setPassword(encodePassword);
        memberEntity.setMobile(phone);

        //设置默认的会员等级ID
        MemberLevelEntity levelEntity = memberLevelService.getBaseMapper().selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        memberEntity.setLevelId(levelEntity.getId());
        memberEntity.setNickname(userName);
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkUserNameUnique(String userName) {
        Integer nameCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (nameCount > 1) {
            //用户名已经存在
            throw new UserNameExsitException();
        }
    }

    @Override
    public void checkPhoneUnique(String phone) {
        Integer mobileCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobileCount > 1) {
            //手机号已经存在
            throw new PhoneExsitException();
        }
    }

    @Override
    public MemberEntity login(UserLoginVo userLoginVo) {
        String password = userLoginVo.getPassword();
//        String phone = userLoginVo.getPhone();
        String userAccount = userLoginVo.getUserAccount();

        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", userAccount).or().eq("mobile", userAccount));
        if (memberEntity == null) {
            //登录失败
            return null;
        } else {
            String encodePassword = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            if (passwordEncoder.matches(password, encodePassword)) {
                //能够匹配的上
                return memberEntity;
            } else {
                return null;
            }
        }
    }

    /**
     * 处理社交登录
     *
     * @param memberEntity
     * @return
     */
    @Override
    public MemberEntity socialLogin(MemberEntity memberEntity) {
        String uid = memberEntity.getSocialUid();
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (entity != null) {
            //之前登录过
            MemberEntity updateEntity = new MemberEntity();
            updateEntity.setId(entity.getId());
            updateEntity.setAccess_token(memberEntity.getAccess_token());
            updateEntity.setExpiresIn(memberEntity.getExpiresIn());
            //通过ID去更新过期时间和token
            baseMapper.updateById(updateEntity);
            return entity;
        } else {
            //首次登录，需要完成注册的功能
            baseMapper.insert(memberEntity);
            return memberEntity;
        }
    }
}